package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@SuppressWarnings("ALL")
/**
 * @Description :
 * @author     :LD
 */
@Service
@Transactional
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {
    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult collectionArticleBehavior(CollectionBehaviorDto dto) {
        //1 检查参数
        if (dto==null||dto.getEntryId()==null||(dto.getOperation()>1||dto.getOperation()<0)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtils.getUser();
        //2 获取行为实体
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.getBehaviorEntry(apUser.getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3 获取收藏文章数据
        ApCollection apCollection = getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getEntryId())
                .eq(ApCollection::getEntryId, apBehaviorEntry.getId()));
        if (apCollection==null){//保存
            apCollection=new ApCollection();
            apCollection.setArticleId(dto.getEntryId());
            apCollection.setEntryId(apBehaviorEntry.getId());
            apCollection.setType(dto.getOperation());
            apCollection.setCollectionTime(new Date());
            apCollection.setPublishedTime(dto.getPublished_time());
            save(apCollection);
        }else {//修改
            if (dto.getOperation()==0){
                apCollection.setCollectionTime(new Date());
            }
            apCollection.setType(dto.getOperation());
            updateById(apCollection);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
